//
//  ProductVC.m
//  Ufan
//
//  Created by yangqingluo on 15/11/22.
//  Copyright © 2015年 yangqingluo. All rights reserved.
//

#import "ProductVC.h"
#import "CrossLineLabel.h"
#import "UFPageView.h"
#import "ProductDetailVC.h"
#import "ProductFirstCell.h"
#import "OrderFillVC.h"
#import "MessageReadManager.h"

@interface ProductVC()<UITableViewDataSource,UITableViewDelegate,UIActionSheetDelegate>

@property (nonatomic, strong) UFProductInfo *productInfo;
@property (nonatomic, strong) UITableView *showTableView;
@property (nonatomic, strong) UFPageView *headPageView;
@property (nonatomic, strong) UIView *bottomBar;
@property (strong, nonatomic) UILabel *priceLabel;

@property (strong, nonatomic) MessageReadManager *messageReadManager;

@end

@implementation ProductVC


- (instancetype)initWithProductInfo:(UFProductInfo *)info{
    self = [super init];
    if (self) {
        self.productInfo = info;
    }
    
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    self.view.backgroundColor = RGBA(245, 245, 245, 1.0);
    [self setupBarButtonItem];
    [self.view addSubview:self.showTableView];
    [self.view addSubview:self.bottomBar];
    
    [self refreshDatasource];
    
}

- (void)setupBarButtonItem{
    self.title = @"商品详情";
    
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 64, 44)];
    [backButton setImage:[UIImage imageNamed:@"nav_back.png"] forState:UIControlStateNormal];
    [backButton setImageEdgeInsets:UIEdgeInsetsMake(12, 0, 12, 48)];
    backButton.tag = 988;
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    [self.navigationItem setLeftBarButtonItem:backItem];
}

-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)refreshDatasource{
    [QKHttpManager getProductWithProductID:self.productInfo.idString couponType:CouponTypeNormal completion:^(NSObject *object, NSError *error){
        if ([object isKindOfClass:[NSDictionary class]]) {
            NSDictionary *respDic = (NSDictionary *)object;
            if ([respDic[@"code"] intValue] == QKHTTP_SUCCESS) {
                self.productInfo = productInfoFormDic(respDic[@"productInfo"]);
                self.priceLabel.text = self.productInfo.price;
                [self reloadHeadView];
                [self.showTableView reloadData];
            }
        }
    }];
}

- (void)reloadHeadView{
    self.headPageView.imageArray = [self.productInfo.imageList copy];
    [self.headPageView reloadData];
}

- (void)tapHeadPageView{
    NSMutableArray *urlArray = [NSMutableArray new];
    
    for (NSObject *object in self.productInfo.imageList) {
        if ([object isKindOfClass:[UFImage class]]) {
            UFImage *uf_image = (UFImage *)object;
            [urlArray addObject:[NSURL URLWithString:uf_image.urlPath]];
        }
    }

    if (urlArray.count) {
        NSInteger index = [self.headPageView indexOfPage];
        [self.messageReadManager showBrowserWithImages:urlArray currentPhotoIndex:(index < urlArray.count - 1) ? index : 0];
    }
}

#pragma response
- (void)buyNow{
    if ([AppPublic shareInstanceApp].Token) {
        if (self.productInfo.itemSelectedIndex < self.productInfo.itemTitleList.count) {
            UFItemTitle *itemTitle = self.productInfo.itemTitleList[self.productInfo.itemSelectedIndex];
            if (self.productInfo.itemList[itemTitle.title]) {
                [AppPublic shareInstanceApp].addressSelected = nil;
                
                OrderFillVC *orderFill = [[OrderFillVC alloc]initWithItem:itemFromDic(self.productInfo.itemList[itemTitle.title])];
                orderFill.productInfo = self.productInfo;
                [self.navigationController pushViewController:orderFill animated:YES];
                
                return;
            }
        }
        
        [self showHint:@"购买失败"];
    }
    else{
        [[AppPublic shareInstanceApp] presentLoginVC:self.navigationController];
    }
    
    
}


- (void)routerEventWithName:(NSString *)eventName userInfo:(NSDictionary *)userInfo{
    if ([eventName isEqualToString:UF_Router_Event_ProductDetailButton]) {
        ProductDetailVC *detailVC = [[ProductDetailVC alloc]initWithInfo:self.productInfo.descriptionString];
        detailVC.title = @"亮点";
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

#pragma getter
- (MessageReadManager *)messageReadManager{
    if (_messageReadManager == nil) {
        _messageReadManager = [MessageReadManager defaultManager];
    }
    
    return _messageReadManager;
}

- (UITableView *)showTableView{
    if (!_showTableView) {
        _showTableView= [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height - TAB_BAR_HEIGHT - STATUS_BAR_HEIGHT) style:UITableViewStylePlain];
        _showTableView.multipleTouchEnabled = YES;
        _showTableView.dataSource = self;
        _showTableView.delegate = self;
        _showTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_showTableView setBackgroundColor:[UIColor clearColor]];
        
        _showTableView.tableHeaderView = self.headPageView;
    }
    
    return _showTableView;
}

- (UFPageView *)headPageView{
    if (!_headPageView) {
        _headPageView = [[UFPageView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.width * 3.0 / 4.0)];
        [_headPageView setBackgroundColor:[UIColor clearColor]];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapHeadPageView)];
        [_headPageView addGestureRecognizer:tap];
    }
    
    return _headPageView;
}

- (UIView *)bottomBar{
    if (!_bottomBar) {
        _bottomBar = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.height - TAB_BAR_HEIGHT - STATUS_BAR_HEIGHT, self.view.width, TAB_BAR_HEIGHT)];
        _bottomBar.backgroundColor = [UIColor whiteColor];
        _bottomBar.layer.shadowColor = [UIColor blackColor].CGColor;
        _bottomBar.layer.shadowOffset = CGSizeMake(0, -1);
        _bottomBar.layer.shadowOpacity = 0.2;
        
        UIButton *buyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        buyButton.frame = CGRectMake(0, 0, 100, 36);
        buyButton.center = CGPointMake(_bottomBar.width - 0.5 * buyButton.width - 10, 0.5 * _bottomBar.height);
        buyButton.titleLabel.font = [UIFont systemFontOfSize:16.0];
        [buyButton setBackgroundColor:[UIColor orangeColor]];
        buyButton.layer.cornerRadius = 5;
        buyButton.layer.masksToBounds = YES;
        [buyButton setTitle:@"立即购买" forState:UIControlStateNormal];
        [buyButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [buyButton addTarget:self action:@selector(buyNow) forControlEvents:UIControlEventTouchUpInside];
        [_bottomBar addSubview:buyButton];
        
        self.priceLabel.center = CGPointMake(buyButton.left - 0.5 * self.priceLabel.width - 20, buyButton.center.y);
        [_bottomBar addSubview:self.priceLabel];
    }
    
    return _bottomBar;
}

- (UILabel *)priceLabel{
    if (!_priceLabel) {
        _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 140, 16)];
        _priceLabel.font = [UIFont systemFontOfSize:18];
        _priceLabel.textAlignment = NSTextAlignmentRight;
        _priceLabel.textColor = [UIColor orangeColor];
    }
    
    return _priceLabel;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        static NSString *CellIdentifier = @"ProductFirstCell";
        ProductFirstCell *cell = (ProductFirstCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        if (cell == nil) {
            cell = [[ProductFirstCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.info = self.productInfo;
        
        
        return cell;
    }
    else if(indexPath.row == 1){
        static NSString *itemCellIdentifier = @"itemCellIdentifier";
        
        UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:itemCellIdentifier];
        
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:itemCellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.textLabel.text = @"已选";
        
        if (self.productInfo.itemSelectedIndex < self.productInfo.itemTitleList.count) {
            UFItemTitle *itemTitle = self.productInfo.itemTitleList[self.productInfo.itemSelectedIndex];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@",itemTitle.value, itemTitle.name];
        }
        
        
        return cell;
    }
    
    
    return [UITableViewCell new];
}


#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return [ProductFirstCell tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    
    return 44;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 1) {
        //规格
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                             destructiveButtonTitle:nil
                                                  otherButtonTitles:nil];
        
        sheet.tag = indexPath.row;
        
        //这样设置，取消按钮的buttonIndex为0
        for (UFItemTitle *itemTitle in self.productInfo.itemTitleList) {
            [sheet addButtonWithTitle:[NSString stringWithFormat:@"%@ %@",itemTitle.value, itemTitle.name]];
        }
        
        // Show the sheet
        [sheet showInView:self.view];
    }
}


#pragma mark - actionsheet delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (actionSheet.tag) {
            //设置规格
        case 1:{
            if (buttonIndex >= 1 && buttonIndex <= self.productInfo.itemTitleList.count) {
                self.productInfo.itemSelectedIndex = buttonIndex - 1;
                [self.showTableView reloadData];
            }
        }
            break;
            
            
        default:
            break;
    }
    
}

@end
